package org.example.scoresystem_backen.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.scoresystem_backen.common.Result;
import org.example.scoresystem_backen.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 简化的JWT认证过滤器
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        String requestPath = request.getRequestURI();
        String method = request.getMethod();

        // OPTIONS预检请求直接放行
        if ("OPTIONS".equals(method)) {
            filterChain.doFilter(request, response);
            return;
        }

        // 登录接口不需要认证
        if (requestPath.contains("/login")) {
            filterChain.doFilter(request, response);
            return;
        }

        // 注册相关接口不需要认证
        if (requestPath.contains("/register") || requestPath.contains("/check-student-id")) {
            filterChain.doFilter(request, response);
            return;
        }

        // 班级选项接口不需要认证（用于注册页面）
        if (requestPath.equals("/api/classes/options")) {
            filterChain.doFilter(request, response);
            return;
        }

        // 学生注册接口不需要认证（POST /api/students）
        if (requestPath.equals("/api/students") && "POST".equals(method)) {
            filterChain.doFilter(request, response);
            return;
        }

        // 健康检查接口不需要认证
        if (requestPath.contains("/test/")) {
            filterChain.doFilter(request, response);
            return;
        }

        // 提取JWT令牌
        String token = extractToken(request);

        if (token == null || !jwtUtil.validateToken(token)) {
            sendError(response, "认证失败");
            return;
        }

        try {
            // 将用户信息存储到请求属性中
            request.setAttribute("userId", jwtUtil.getUserIdFromToken(token));
            request.setAttribute("username", jwtUtil.getUsernameFromToken(token));
            request.setAttribute("userType", jwtUtil.getUserTypeFromToken(token));

            filterChain.doFilter(request, response);

        } catch (Exception e) {
            sendError(response, "令牌解析失败");
        }
    }

    /**
     * 从请求头中提取JWT令牌
     */
    private String extractToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }

    /**
     * 发送错误响应
     */
    private void sendError(HttpServletResponse response, String message) throws IOException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");

        Result<Object> result = Result.error(message);
        String jsonResponse = objectMapper.writeValueAsString(result);

        response.getWriter().write(jsonResponse);
        response.getWriter().flush();
    }
}
